/**
 * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.sms.service.impl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.springblade.common.constant.RoleIdConstant;
import org.springblade.core.mp.base.BaseEntity;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.utils.*;
import org.springblade.modules.sms.entity.Sms;
import org.springblade.modules.sms.vo.SmsVO;
import org.springblade.modules.sms.mapper.SmsMapper;
import org.springblade.modules.sms.service.ISmsService;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.mapper.UserMapper;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 短信配置表 服务实现类
 *
 * @author Blade
 * @since 2020-12-13
 */
@Service
@AllArgsConstructor
public class SmsServiceImpl extends BaseServiceImpl<SmsMapper, Sms> implements ISmsService {

	private final RedisUtil redisUtil;
	private final UserMapper userMapper;


	@Override
	public IPage<SmsVO> selectSmsPage(IPage<SmsVO> page, Sms sms) {
		List<SmsVO> smsList = baseMapper.selectSmsPage(page, sms);
		List<SmsVO> smsVOS = new ArrayList<>();
		for (SmsVO smsVO : smsList) {
			smsVO.setIsUse(smsVO.getStatus()==0?"启用":"停用");
			smsVOS.add(smsVO);
		}
		return page.setRecords(smsVOS);
	}

	/**
	 * 发送短信配置
	 * @param phone
	 * @param code
	 * @return
	 */
	public boolean sendSms(String phone,String code) {
		Long userId = Func.isEmpty(SecureUtil.getUser())?Func.toLong(RoleIdConstant.ADMIN_ID):SecureUtil.getUserId();
		Sms sms = baseMapper.selectOne(Wrappers.<Sms>query().lambda()
				.eq(BaseEntity::getStatus, 0)
				.eq(BaseEntity::getCreateUser, userId));
		//用户AccessKey
		//id
		String accessKeyId=sms.getAccessKeyId();
		//密码
		String accessSecret=sms.getAccessSecret();
		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
		IAcsClient client = new DefaultAcsClient(profile);
		CommonRequest request = new CommonRequest();
		request.setSysMethod(MethodType.POST);
		request.setSysDomain("dysmsapi.aliyuncs.com");
		request.setSysVersion("2017-05-25");
		request.setSysAction("SendSms");
		request.putQueryParameter("RegionId", "cn-hangzhou");
		request.putQueryParameter("PhoneNumbers", phone);
		request.putQueryParameter("SignName", sms.getSignName());
		request.putQueryParameter("TemplateCode", sms.getTemplateCode());
		request.putQueryParameter("TemplateParam", "{\"code\":"+code+"}");
		try {
			CommonResponse response = client.getCommonResponse(request);
			System.out.println(response.getData());
		} catch (ServerException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		}
		return true;
	}


	/**
	 * 发送短信，并存入redis
	 * @param phone
	 * @return
	 */
	@Override
	public boolean smsPhone(String phone) {
		String code = StringUtil.random(6, RandomType.INT);
		boolean sendSms = sendSms(phone, code);
		redisUtil.set("sms:"+phone,code,5, TimeUnit.MINUTES);
		return sendSms;
	}

	/**
	 * 从redis取出验证码，验证，正确？删除：保存
	 * @param phone
	 * @param code
	 * @return
	 */
	@Override
	public boolean smsMessage(String phone, String code) {
		Object redis = redisUtil.get("sms:"+phone);
		boolean equals = code.equals(redis);
		if (equals){
			redisUtil.del("sms:"+phone);
		}
		return equals;
	}

	@Override
	public boolean smsStart(Long id) {
		List<Sms> list = list(Wrappers.<Sms>query().lambda().ne(Sms::getId,id));
		for (Sms sms : list) {
			sms.setStatus(1);
			updateById(sms);
		}
		Sms sms = getById(id);
		sms.setStatus(0);
		updateById(sms);
		return true;
	}

}
